package com.ikangtai.shecare.curve;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.ChartImgUserMessageUtil;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.IndexCount;
import com.ikangtai.shecare.common.util.XYLineMsg;
import com.ikangtai.shecare.record.bean.UserRecordData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by ikangtai on 2016/5/31.
 */
public class SaveChartImg2Local {

    int count = 1;
    private static final int WIDTH = 1487;
    private static final int HEIGHT = 2105;
    int unitlength = 20;
    float hUnitlength = 20;
    float wUnitlength = 28.6f;
    float textSize = 15;
    Paint paint = new Paint();
    Bitmap bmp;
    Canvas canvas;
    JSONArray array;
    private List<ChartImgUserMessageUtil> userMessageList;
    private List<ChartImgUserMessageUtil> setUserMessageList;
    private List<IndexCount> periodBeginIndexList; // 标记有经期开始的位置数的集合
    private List<XYLineMsg> xyLineMsgList;
    private int userCycleCount;
    private int periodTypeSection = 0;
    private int[] yHeightPositionList = {140, 750, 1360};
    private int xDefaultPosition = 100;

    Context context;

    /**
     * 异步获取数据并绘制表格
     */
    public void getUserMsgAndDrawTable(final Context context) {
        this.context = context;
        this.bmp = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);
        this.canvas = new Canvas(bmp);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray getData4Local = getData4LocalImg(context, 3);
                    if (getData4Local.length() != 0) {
                        drawTableMain(getData4Local);
                    } else {
                        Looper.prepare();
                        Toast.makeText(context, "亲~数据太少哦~", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * NOTE: 请在开启的子线程中调用此函数！！
     *
     * @param periodCount 要画的周期数
     * @return JSON格式的画图数据，格式如下：
     * <p/>
     * [{"date":"2016-06-01", "temperature":"36.89", "periodType":"jyq", "isYjqStart":true,
     * "hadSex": 1, "condition": int型组合数据}, ...]
     * <p/>
     * 注意：
     * 1) temperature若无值，则为"-"
     * 2) periodType为DayUnitDSOutput类里获取的PERIOD_XXQ值类型
     * 3) hadSex为 1 表示同房， 0 表示不同房
     */
    private JSONArray getData4LocalImg(Context context, int periodCount) {
        JSONArray data4LocalImgJsonArray = new JSONArray();

        int alDayNum = App.dayUnitDSOutputsList.size();

        String today = DateUtil.getSimpleDate();
        boolean startRetrieveData = false; //是否开始获取数据，只有当指向当天时才开始向前移动获取算法数据
        DayUnitDSOutput dayUnitDSOutput;

        String alDateStr;
        String temperature;
        String periodType;
        int hadSex;
        int condition;

        int periodNum = 0;

        for (int i = alDayNum-1; i >= 0; i--) {
            dayUnitDSOutput = App.dayUnitDSOutputsList.get(i);
            alDateStr = DateUtil.getSimpleCircleCalendarTopDate(dayUnitDSOutput.date);

            if (!startRetrieveData) {
                if (alDateStr.equals(DateUtil.getSimpleDateAddOneDay(today,1)))
                    startRetrieveData = true;
                else
                    continue;
            } else {
                //开始获取periodCount个周期的数据
                AppLog.i("start retrieve data for saving local image of BBT curve!");

                JSONObject dayJSONObject = new JSONObject();
                dayUnitDSOutput = App.dayUnitDSOutputsList.get(i);

                alDateStr = DateUtil.getSimpleCircleCalendarTopDate(dayUnitDSOutput.date);
                UserRecordData userRecordData = new UserRecordData(context, dayUnitDSOutput.date, App.userName);
                temperature = String.valueOf(userRecordData.getBBT());
                periodType = dayUnitDSOutput.getPeriod(App.status);
                hadSex = userRecordData.isCopulationHaveSex() ? 1 : 0;
                condition = userRecordData.getSymptomInfo();
                boolean isYjqStart = isYjqStart(i);

                try {
                    dayJSONObject.put("date", alDateStr);
                    dayJSONObject.put("temperature", temperature);
                    dayJSONObject.put("periodType", periodType);
                    dayJSONObject.put("isYjqStart", isYjqStart);
                    dayJSONObject.put("hadSex", hadSex);
                    dayJSONObject.put("condition", condition);
                    dayJSONObject.put("isSick", userRecordData.isSick());
                    dayJSONObject.put("isDrunk", userRecordData.isDrunk());
                    dayJSONObject.put("isLongTrip", userRecordData.isLongTrip());
                    dayJSONObject.put("isLostSleep", userRecordData.isLostSleep());
                    dayJSONObject.put("isFever", userRecordData.isFever());
                    dayJSONObject.put("isNonMensesBlood", userRecordData.isNonMensesBlood());
                    dayJSONObject.put("isDizzy", userRecordData.isDizzy());
                    dayJSONObject.put("isBackAche", userRecordData.isBackAche());
                    dayJSONObject.put("isAnxious", userRecordData.isAnxious());
                    dayJSONObject.put("isBellyAche", userRecordData.isBellyAche());
                    dayJSONObject.put("isHeadache", userRecordData.isHeadache());
                    dayJSONObject.put("isBreastAche", userRecordData.isBreastAche());
                    dayJSONObject.put("isBodyAche", userRecordData.isBodyAche());
                    dayJSONObject.put("isMeasureLate", userRecordData.isMeasureLate());
                    dayJSONObject.put("isJetLag", userRecordData.isJetLag());
                    dayJSONObject.put("isHolidayOutofLife", userRecordData.isHolidayOutofLife());
                    dayJSONObject.put("isWeatherChange", userRecordData.isWeatherChange());
                    dayJSONObject.put("isBigPressure", userRecordData.isBigPressure());
                    dayJSONObject.put("isTooExcited", userRecordData.isTooExcited());

                    data4LocalImgJsonArray.put(dayJSONObject);
                    AppLog.i("dayJSONObject = " + dayJSONObject.toString());
                } catch (JSONException e) {
                    AppLog.e("getData4LocalImg JSONException!");
                    e.printStackTrace();
                }

                if (periodNum < periodCount) {
                    if (isYjqStart)
                        periodNum++;
                } else
                    break;
            }
        }

        AppLog.i("retrieve data for saving local image of BBT curve completed!");
        return data4LocalImgJsonArray;
    }

    private boolean isYjqStart(int i) {
        DayUnitDSOutput dayUnitDSOutput = App.dayUnitDSOutputsList.get(i);
        boolean isYjqStart = false;

        if (dayUnitDSOutput.getPeriod(App.status).equals(DayUnitDSOutput.PERIOD_YJQ)) {
            if (i == 0)
                isYjqStart = true;
            else {
                if (!App.dayUnitDSOutputsList.get(i - 1).getPeriod(App.status).equals(DayUnitDSOutput.PERIOD_YJQ))
                    isYjqStart = true;
            }
        }

        return isYjqStart;
    }

    /**
     * 绘制报表主要入口
     *
     * @param array
     * @throws JSONException
     */
    private void drawTableMain(JSONArray array) throws JSONException {
        drawTableUserMessageList(array);//过滤用户有效的数据信息
        drawTableInfo();//绘制固定初始化图形及文字
        drawTableGetUserCycleCount();//统计用户周期数
        drawTableAction();//开始绘制曲线以及相关数据
        drawTableEnd();//绘制结束并保存成图片
    }

    /**
     * 过滤用户有效的数据信息
     *
     * @param array
     * @throws JSONException
     */
    private void drawTableUserMessageList(JSONArray array) throws JSONException {
        userMessageList = new ArrayList<ChartImgUserMessageUtil>();//过滤用户有效的数据信息
        for (int i = array.length() - 1; i >= 0; i--) {
            ChartImgUserMessageUtil userMessage = new ChartImgUserMessageUtil();
            JSONObject resultMessage = array.getJSONObject(i);
            String uDate = resultMessage.getString("date");
            String uYear = uDate.substring(0, 4);
            String uMonth = uDate.substring(5, 7);
            String uDay = uDate.substring(8, 10);
            // 给实体类赋值
            userMessage.setDate(uDate);
            userMessage.setYear(Integer.parseInt(uYear));
            userMessage.setMonth(Integer.parseInt(uMonth));
            userMessage.setDay(Integer.parseInt(uDay));
            userMessage.setTemperature(resultMessage.getDouble("temperature"));
            userMessage.setPeriodType(resultMessage.getString("periodType"));
            userMessage.setHadSex(resultMessage.getInt("hadSex"));
            userMessage.setCondition(resultMessage.getInt("condition"));
            userMessage.setIsYjqStart(resultMessage.getBoolean("isYjqStart"));

            userMessage.setSick(resultMessage.getBoolean("isSick"));
            userMessage.setDrunk(resultMessage.getBoolean("isDrunk"));
            userMessage.setLongTrip(resultMessage.getBoolean("isLongTrip"));
            userMessage.setLostSleep(resultMessage.getBoolean("isLostSleep"));
            userMessage.setFever(resultMessage.getBoolean("isFever"));
            userMessage.setNonMensesBlood(resultMessage.getBoolean("isNonMensesBlood"));
            userMessage.setDizzy(resultMessage.getBoolean("isDizzy"));
            userMessage.setBackAche(resultMessage.getBoolean("isBackAche"));
            userMessage.setAnxious(resultMessage.getBoolean("isAnxious"));
            userMessage.setBellyAche(resultMessage.getBoolean("isBellyAche"));
            userMessage.setHeadache(resultMessage.getBoolean("isHeadache"));
            userMessage.setBreastAche(resultMessage.getBoolean("isBreastAche"));
            userMessage.setBodyAche(resultMessage.getBoolean("isBodyAche"));
            userMessage.setMeasureLate(resultMessage.getBoolean("isMeasureLate"));
            userMessage.setJetLag(resultMessage.getBoolean("isJetLag"));
            userMessage.setHolidayOutofLife(resultMessage.getBoolean("isHolidayOutofLife"));
            userMessage.setWeatherChange(resultMessage.getBoolean("isWeatherChange"));
            userMessage.setBigPressure(resultMessage.getBoolean("isBigPressure"));
            userMessage.setTooExcited(resultMessage.getBoolean("isTooExcited"));

            userMessageList.add(userMessage);

        }

    }

    /**
     * 统计用户周期数
     */
    private void drawTableGetUserCycleCount() {
        periodBeginIndexList = new ArrayList<IndexCount>();
        for (int i = 0; i < userMessageList.size(); i++) {
            IndexCount indexCount = new IndexCount();
            if (userMessageList.get(i).getIsYjqStart()) { // PeriodType为1时，表示经期开始，并且取出其下角标数
                indexCount.setIndex(i);
                periodBeginIndexList.add(indexCount);
            }
        }

        userCycleCount = periodBeginIndexList.size();
    }

    /**
     * 开始绘制曲线以及相关数据
     */
    private void drawTableAction() {
        if (userCycleCount > 3) {//用户周期数大于3个
            drawUserMsg(userCycleCount - 3);
        } else {
            drawUserMsg(0);
        }
    }

    /**
     * 绘制结束并保存成图片
     */
    private void drawTableEnd() {
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        String strFile = Environment.getExternalStorageDirectory().getPath() + "/mychart.jpg";
        saveBitmap(bmp, strFile);
    }

    /**
     * 绘制固定初始化图形及文字
     */
    private void drawTableInfo() {
        canvas.drawColor(Color.WHITE);
        paint.setAntiAlias(true);//除锯齿

        drawInfoMsg();//初始化信息绘制

        for (int i = 0; i < 3; i++) {//绘制空白表格
            drawTable(xDefaultPosition, yHeightPositionList[i]);
        }
    }

    /**
     * 绘制图表
     */
    private void drawTable(int x, int y) {
        count = 1;
        drawHorizonalLine(x, y);
        drawHorizonalLineText(x, y);
        drawVerticalLine(x, y);
        drawVerticalLineCycle(x, y);
    }

    /**
     * 初始化信息绘制
     */
    private void drawInfoMsg() {
        drawTitle();
        drawFootText();
        drawSexIcon();
//        drawIllIcon();
//        drawInsomniaIcon();
//        drawMenstruationIcon();
//        drawDrunkIcon();
//        drawPlaneIcon();
    }

    /**
     * 绘制标题
     */
    private void drawTitle() {
//        paint.setColor(Color.rgb(240, 240, 240));
//        RectF rect = new RectF(200, 200, 1800, 3400);
//        canvas.drawRect(rect, paint);

        paint.setColor(Color.BLACK);
        paint.setTextSize(30);
        canvas.drawText(context.getString(R.string.bbtexcel), 603, 100, paint);

        paint.setTextSize(20);
//        canvas.drawText(context.getString(R.string.namef), 950, 75, paint);
    }

    /**
     * 绘制标题中的日期
     */
    private void drawTitleDate(int beginIndex, int endIndex) {
        paint.setTextSize(20);
        canvas.drawText(context.getString(R.string.datef) + userMessageList.get(periodBeginIndexList.get(beginIndex).getIndex()).getDate().substring(0, 7) + "  -  " + userMessageList.get(periodBeginIndexList.get(endIndex).getIndex()).getDate().substring(0, 7), 950, 120, paint);
    }

    /**
     * 绘制底部图示
     */
    private void drawFootText() {
        canvas.drawText(context.getString(R.string.note), xDefaultPosition, 1955, paint);

        canvas.drawText(context.getString(R.string.my_chart_isCopulationHaveSex), 165, 1955, paint);
        canvas.drawText(context.getString(R.string.my_chart_isSick), 140, 1985, paint);
        canvas.drawText(context.getString(R.string.my_chart_isDrunk), 140, 2015, paint);
        canvas.drawText(context.getString(R.string.my_chart_isLongTrip), 140, 2045, paint);
        canvas.drawText(context.getString(R.string.my_chart_isLostSleep), 140, 2075, paint);

        canvas.drawText(context.getString(R.string.my_chart_isFever), 320, 1955, paint);
        canvas.drawText(context.getString(R.string.my_chart_isNonMensesBlood), 320, 1985, paint);
        canvas.drawText(context.getString(R.string.my_chart_isDizzy), 320, 2015, paint);
        canvas.drawText(context.getString(R.string.my_chart_isBackAche), 320, 2045, paint);
        canvas.drawText(context.getString(R.string.my_chart_isAnxious), 320, 2075, paint);

        canvas.drawText(context.getString(R.string.my_chart_isBellyAche), 500, 1955, paint);
        canvas.drawText(context.getString(R.string.my_chart_isHeadache), 500, 1985, paint);
        canvas.drawText(context.getString(R.string.my_chart_isBreastAche), 500, 2015, paint);
        canvas.drawText(context.getString(R.string.my_chart_isBodyAche), 500, 2045, paint);
        canvas.drawText(context.getString(R.string.my_chart_isMeasureLate), 500, 2075, paint);

        canvas.drawText(context.getString(R.string.my_chart_isJetLag), 680, 1955, paint);
        canvas.drawText(context.getString(R.string.my_chart_isHolidayOutofLife), 680, 1985, paint);
        canvas.drawText(context.getString(R.string.my_chart_isWeatherChange), 680, 2015, paint);
        canvas.drawText(context.getString(R.string.my_chart_isBigPressure), 680, 2045, paint);
        canvas.drawText(context.getString(R.string.my_chart_isTooExcited), 680, 2075, paint);

        canvas.drawText(context.getString(R.string.my_chart_period), 860, 1955, paint);

        paint.setTextSize(50);
        canvas.drawText(context.getString(R.string.app_icon_label_release), 1287, 1980, paint);
        paint.setTextSize(25);
        canvas.drawText(context.getString(R.string.help_you_easily_for_pregnancy), 1237, 2020, paint);
    }

    /**
     * 绘制同房标识
     */
    private void drawSexIcon() {
        canvas.drawCircle(150, 1950, 4, paint);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        canvas.drawCircle(150, 1950, 9, paint);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(2);
    }

    /**
     * 绘制生病标识
     */
    private void drawIllIcon() {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.chart_got_ill_icon);
        Matrix matrix = new Matrix();
        matrix.postScale(0.1f, 0.1f);
        Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, 140, 1968, paint);
    }

    /**
     * 绘制熬夜标识
     */
    private void drawInsomniaIcon() {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.chart_insomnia_icon);
        Matrix matrix = new Matrix();
        matrix.postScale(0.1f, 0.1f);
        Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, 140, 1998, paint);
    }

    /**
     * 绘制经期标识
     */
    private void drawMenstruationIcon() {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.chart_in_menstruation_icon);
        Matrix matrix = new Matrix();
        matrix.postScale(0.25f, 0.25f);
        Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, 330, 1940, paint);
    }

    /**
     * 绘制喝酒标识
     */
    private void drawDrunkIcon() {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.chart_got_drunk_icon);
        Matrix matrix = new Matrix();
        matrix.postScale(0.1f, 0.1f);
        Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, 330, 1968, paint);
    }

    /**
     * 绘制旅行标识
     */
    private void drawPlaneIcon() {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.chart_plane_icon);
        Matrix matrix = new Matrix();
        matrix.postScale(0.1f, 0.1f);
        Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        canvas.drawBitmap(dstbmp, 330, 1998, paint);
    }

    /**
     * 绘制横线
     */
    private void drawHorizonalLine(int x, int y) {
        paint.setColor(Color.rgb(170, 170, 170));
        paint.setStrokeWidth(2);
        //绘制横线
        for (int i = 0; i < 29; i++) {
            if (i < 4) {
                canvas.drawLine(x, y + i * hUnitlength, x + 45 * wUnitlength, y + i * hUnitlength, paint);
            } else if (i > 3 && i < 24) {
                canvas.drawLine(x + 3 * wUnitlength, y + i * hUnitlength, x + 45 * wUnitlength, y + i * hUnitlength, paint);
            } else if (i == 24) {
                canvas.drawLine(x, y + i * hUnitlength, x + 45 * wUnitlength, y + i * hUnitlength, paint);
            } else if (i == 28) {
                canvas.drawLine(x, y + i * hUnitlength, x + 45 * wUnitlength, y + i * hUnitlength, paint);
            }
        }
    }

    /**
     * 绘制横线上的标识文字
     */
    private void drawHorizonalLineText(int x, int y) {
        paint.setColor(Color.BLACK);
        paint.setTextSize(textSize);
        for (int i = 0; i < 31; i++) {
            if (i == 1) {
                canvas.drawText(context.getString(R.string.month), x + wUnitlength + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 2) {
                canvas.drawText(context.getString(R.string.day), x + wUnitlength + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 3) {
                canvas.drawText(context.getString(R.string.personal_health_info_menses_period_str), x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 4) {
                canvas.drawText(context.getString(R.string.body_temperature), x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 5) {
                canvas.drawText("     .4", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 6) {
                canvas.drawText("     .3", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 7) {
                canvas.drawText("     .2", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 8) {
                canvas.drawText("     .1", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 9) {
                canvas.drawText("37.0", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 10) {
                canvas.drawText("     .9", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 11) {
                canvas.drawText("     .8", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 12) {
                canvas.drawText("     .7", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 13) {
                canvas.drawText("     .6", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 14) {
                canvas.drawText("36.5", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 15) {
                canvas.drawText("     .4", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 16) {
                canvas.drawText("     .3", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 17) {
                canvas.drawText("     .2", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 18) {
                canvas.drawText("     .1", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 19) {
                canvas.drawText("36.0", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 20) {
                canvas.drawText("     .9", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 21) {
                canvas.drawText("     .8", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 22) {
                canvas.drawText("     .7", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 23) {
                canvas.drawText("     .6", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 24) {
                canvas.drawText("35.5", x + 18 + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 26) {
                canvas.drawText(context.getString(R.string.bei), x + wUnitlength + 1, y + i * hUnitlength - 5, paint);
            } else if (i == 27) {
                canvas.drawText(context.getString(R.string.zhu), x + wUnitlength + 1, y + i * hUnitlength - 5, paint);
            }
        }
    }

    /**
     * 绘制竖线
     */
    private void drawVerticalLine(int x, int y) {
        paint.setColor(Color.rgb(170, 170, 170));
        paint.setStrokeWidth(2);
        //绘制竖线
        for (int i = 0; i < 46; i++) {
            if (i > 0 && i < 3) {

            } else if (i > 3 && i < 45) {
                canvas.drawLine(x + i * wUnitlength, y + hUnitlength, x + i * wUnitlength, y + 28 * hUnitlength - 80, paint);
            } else {
                canvas.drawLine(x + i * wUnitlength, y, x + i * wUnitlength, y + 28 * hUnitlength, paint);
            }
        }
    }


    /**
     * 绘制报表
     *
     * @param indexBegin
     */
    public void drawUserMsg(int indexBegin) {
        setUserMessageList = new ArrayList<ChartImgUserMessageUtil>();
//        trangleUpList = new ArrayList<XYLineMsg>();
//        trangleDownList = new ArrayList<XYLineMsg>();
        xyLineMsgList = new ArrayList<XYLineMsg>();
//        getDateList = new ArrayList<GetDate>();
        int yHeightPositionListIndex = 0;
        int forCount=0;
        for (int i = indexBegin; i < userCycleCount; i++) {
            int unitCount = 0;
            String date = userMessageList.get(periodBeginIndexList.get(i).getIndex()).getDate().substring(0, 10);// 获得周期开始的日期，userMessageList表示用户所有数据集合，indexList表示经期开始脚标数集合
            if ((i + 1) == userCycleCount) {
                forCount = daysBetween(getDate(i), userMessageList.get(userMessageList.size() - 1).getDate()) + 1;
                setDrawUserMsgList(userMessageList.size(), unitCount, date, yHeightPositionListIndex, i, forCount);
            } else {
                forCount = daysBetween(getDate(i), getDate(i + 1));
                setDrawUserMsgList(periodBeginIndexList.get(i + 1).getIndex(), unitCount, date, yHeightPositionListIndex, i, forCount);
            }

            drawCircle();//绘制点
            drawCircleLine();//绘制折线
            drawVerticalLineDay(xDefaultPosition, yHeightPositionList[yHeightPositionListIndex],forCount);//绘制日期
            drawVerticalLineMonth(xDefaultPosition, yHeightPositionList[yHeightPositionListIndex]);//绘制月份
            drawNote(xDefaultPosition, yHeightPositionList[yHeightPositionListIndex]);//绘制备注
            drawPeriod(xDefaultPosition, yHeightPositionList[yHeightPositionListIndex]);//绘制经期

            yHeightPositionListIndex = yHeightPositionListIndex + 1;
            setUserMessageList.clear();
            xyLineMsgList.clear();
            periodTypeSection = 0;
        }

        drawTitleDate(indexBegin, userCycleCount - 1);//绘制头部日期
    }

    /**
     * 将用户数据计算成坐标并将其保存到数组中
     *
     * @param index
     * @param unitCount
     * @param date
     * @param yHeightPositionListIndex
     * @param i
     * @param forCount
     */
    public void setDrawUserMsgList(int index, int unitCount, String date, int yHeightPositionListIndex, int i, int forCount) {
        int indexCount = periodBeginIndexList.get(i).getIndex();

        int periodTypeFlag = 0;// 标记经期
        String periodTypeDate = null;

        if (forCount > 40) {
            forCount = 40;
        }
        for (int j = 0; j < forCount; j++) {
            ChartImgUserMessageUtil setUserMessage = new ChartImgUserMessageUtil();
            XYLineMsg trangleUpMsg = new XYLineMsg();
            XYLineMsg trangleDownMsg = new XYLineMsg();
            setUserMessage.setDate(date);
            XYLineMsg xyLineMsg = new XYLineMsg();
            for (int jj = indexCount; jj < index; jj++) {
                if (((userMessageList.get(jj).getDate()).substring(0, 10)).equals(date)) {
                    if (userMessageList.get(jj).getTemperature() <= 37.6 && userMessageList.get(jj).getTemperature() >= 35.5) {
                        xyLineMsg.setX(xDefaultPosition + 3*wUnitlength + wUnitlength * unitCount + wUnitlength/2);
                        xyLineMsg.setY((float) (yHeightPositionList[yHeightPositionListIndex] + 28 * hUnitlength - (((userMessageList.get(jj).getTemperature()) - 35.5f) * 10 * 20 + 80)));
                        xyLineMsg.setHadSex(userMessageList.get(jj).getHadSex());

                        xyLineMsgList.add(xyLineMsg);
                    }
//                    setUserMessage.setInsomnia(daily(1, jj));
//                    setUserMessage.setMedicine(daily(2, jj));
//                    setUserMessage.setIll(daily(3, jj));
//                    setUserMessage.setDrink(daily(4, jj));

                    setUserMessage.setSick(userMessageList.get(jj).isSick());
                    setUserMessage.setDrunk(userMessageList.get(jj).isDrunk());
                    setUserMessage.setLongTrip(userMessageList.get(jj).isLongTrip());
                    setUserMessage.setLostSleep(userMessageList.get(jj).isLostSleep());
                    setUserMessage.setFever(userMessageList.get(jj).isFever());
                    setUserMessage.setNonMensesBlood(userMessageList.get(jj).isNonMensesBlood());
                    setUserMessage.setDizzy(userMessageList.get(jj).isDizzy());
                    setUserMessage.setBackAche(userMessageList.get(jj).isBackAche());
                    setUserMessage.setAnxious(userMessageList.get(jj).isAnxious());
                    setUserMessage.setBellyAche(userMessageList.get(jj).isBellyAche());
                    setUserMessage.setHeadache(userMessageList.get(jj).isHeadache());
                    setUserMessage.setBreastAche(userMessageList.get(jj).isBreastAche());
                    setUserMessage.setBodyAche(userMessageList.get(jj).isBodyAche());
                    setUserMessage.setMeasureLate(userMessageList.get(jj).isMeasureLate());
                    setUserMessage.setJetLag(userMessageList.get(jj).isJetLag());
                    setUserMessage.setHolidayOutofLife(userMessageList.get(jj).isHolidayOutofLife());
                    setUserMessage.setWeatherChange(userMessageList.get(jj).isWeatherChange());
                    setUserMessage.setBigPressure(userMessageList.get(jj).isBigPressure());
                    setUserMessage.setTooExcited(userMessageList.get(jj).isTooExcited());

                    if (userMessageList.get(jj).getPeriodType().equals("yjq")) {
                        periodTypeSection = periodTypeSection + 1;
//                        periodTypeFlag = 1;
//                        periodTypeDate = userMessageList.get(jj).getDate();
                    }
                }
            }
            setUserMessageList.add(setUserMessage);
            date = addDateDay(date);
            unitCount = unitCount + 1;
        }

//        if (periodTypeFlag == 1) {
//            periodTypeSection = daysBetween(getDate(i), periodTypeDate);
//        } else {
//            periodTypeSection = 5;
//        }
    }

    /**
     * 绘制具体月份
     */
    private void drawVerticalLineMonth(int x, int y) {
        paint.setTextSize(15);
        paint.setFakeBoldText(false);
        paint.setColor(Color.BLACK);
        canvas.drawText(DateUtil.getSimpleDateForMonth(setUserMessageList.get(0).getDate())+context.getString(R.string.month), x + 3 * wUnitlength + 1, y + hUnitlength - 5, paint);
    }

    /**
     * 绘制具体日期
     */
    private void drawVerticalLineDay(int x, int y,int forCount) {
        paint.setTextSize(15);
        paint.setFakeBoldText(false);
        paint.setColor(Color.BLACK);
        String date = setUserMessageList.get(0).getDate().substring(0, 10);
        for (int i = 0; i < forCount+3; i++) {
            if (i >= 3 && i < 45) {
                canvas.drawText(date.substring(8, 10), x + i * wUnitlength + (wUnitlength-textSize)/2, y + 2 * hUnitlength - 5, paint);
                if((date.substring(8, 10)).equals("01")){
                    canvas.drawText(DateUtil.getSimpleDateForMonth(date)+context.getString(R.string.month), x + i * wUnitlength + 1, y + hUnitlength - 5, paint);
                }
                date = addDateDay(date);
            }
        }
    }

    /**
     * 绘制周期数
     */
    private void drawVerticalLineCycle(int x, int y) {
        paint.setTextSize(15);
        paint.setFakeBoldText(false);
        paint.setColor(Color.BLACK);
        for (int i = 0; i < 46; i++) {
            if (i >= 3 && i < 45) {
                canvas.drawText(""+count, x + i * wUnitlength + (wUnitlength-textSize)/2, y + 3 * hUnitlength - 5, paint);
                count = count + 1;
            }
        }
    }

    /**
     * 绘制圆点
     */
    private void drawCircle() {
        paint.setColor(Color.rgb(0, 0, 0));
//        paint.setColor(Color.rgb(37, 118, 200));
        for (int i = 0; i < xyLineMsgList.size(); i++) {
            if (xyLineMsgList.get(i).getHadSex() == 1) {
                canvas.drawCircle(xyLineMsgList.get(i).getX(), xyLineMsgList.get(i).getY(), 3, paint);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeWidth(2);
                canvas.drawCircle(xyLineMsgList.get(i).getX(), xyLineMsgList.get(i).getY(), 8, paint);
                paint.setStyle(Paint.Style.FILL);
                paint.setStrokeWidth(2);
            } else {
                canvas.drawCircle(xyLineMsgList.get(i).getX(), xyLineMsgList.get(i).getY(), 5, paint);
            }
        }
    }

    /**
     * 绘制圆点连接线
     */
    private void drawCircleLine() {
        paint.setColor(Color.rgb(0, 0, 0));
        paint.setStrokeWidth(2);
        for (int i = 0; i < xyLineMsgList.size() - 1; i++) {
            canvas.drawLine(xyLineMsgList.get(i).getX(), xyLineMsgList.get(i).getY(), xyLineMsgList.get(i + 1).getX(), xyLineMsgList.get(i + 1).getY(), paint);
        }
    }

    /**
     * 绘制备注
     */
    private void drawNote(int x, int y) {
        List noteStringList = new ArrayList();
        for (int i = 0; i < setUserMessageList.size(); i++) {
            if(setUserMessageList.get(i).isSick()){
                noteStringList.add("①");
            }
            if(setUserMessageList.get(i).isDrunk()){
                noteStringList.add("②");
            }
            if(setUserMessageList.get(i).isLongTrip()){
                noteStringList.add("③");
            }
            if(setUserMessageList.get(i).isLostSleep()){
                noteStringList.add("④");
            }
            if(setUserMessageList.get(i).isFever()){
                noteStringList.add("⑤");
            }
            if(setUserMessageList.get(i).isNonMensesBlood()){
                noteStringList.add("⑥");
            }
            if(setUserMessageList.get(i).isDizzy()){
                noteStringList.add("⑦");
            }
            if(setUserMessageList.get(i).isBackAche()){
                noteStringList.add("⑧");
            }
            if(setUserMessageList.get(i).isAnxious()){
                noteStringList.add("⑨");
            }
            if(setUserMessageList.get(i).isBellyAche()){
                noteStringList.add("⑩");
            }
            if(setUserMessageList.get(i).isHeadache()){
                noteStringList.add("⑪");
            }
            if(setUserMessageList.get(i).isBreastAche()){
                noteStringList.add("⑫");
            }
            if(setUserMessageList.get(i).isBodyAche()){
                noteStringList.add("⑬");
            }
            if(setUserMessageList.get(i).isMeasureLate()){
                noteStringList.add("⑭");
            }
            if(setUserMessageList.get(i).isJetLag()){
                noteStringList.add("⑮");
            }
            if(setUserMessageList.get(i).isHolidayOutofLife()){
                noteStringList.add("⑯");
            }
            if(setUserMessageList.get(i).isWeatherChange()){
                noteStringList.add("⑰");
            }
            if(setUserMessageList.get(i).isBigPressure()){
                noteStringList.add("⑱");
            }
            if(setUserMessageList.get(i).isTooExcited()){
                noteStringList.add("⑲");
            }

            paint.setTextSize(18);
            paint.setFakeBoldText(false);
            if(noteStringList.size()>4){
                for (int noteCount=0;noteCount<4;noteCount++){
                    canvas.drawText(noteStringList.get(noteCount).toString(), x + 3 * wUnitlength + i * wUnitlength + (wUnitlength-18)/2, y + (25+noteCount) * unitlength-2 , paint);
                }
            }else if(noteStringList.size()>0 && noteStringList.size()<=4){
                for (int noteCount=0;noteCount<noteStringList.size();noteCount++){
                    canvas.drawText(noteStringList.get(noteCount).toString(), x + 3 * wUnitlength + i * wUnitlength + (wUnitlength-18)/2, y + (25+noteCount) * unitlength-2 , paint);
                }
            }
            noteStringList.clear();
        }
    }

    /**
     * 绘制经期
     */
    private void drawPeriod(int x, int y) {
        for (int i = 0; i < periodTypeSection; i++) {

            paint.setTextSize(20);
            paint.setFakeBoldText(true);
            canvas.drawText(context.getString(R.string.my_chart_isPeriod), x + 3 * wUnitlength + i * wUnitlength+(wUnitlength-20)/2 , y + 24 * hUnitlength-1 , paint);

        }
    }

    /**
     * 保存图片
     *
     * @param bmp
     * @param strFileName
     */
    private void saveBitmap(Bitmap bmp, String strFileName) {
        File file = new File(strFileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, "mychart", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File("/storage/emulated/0/mychart.jpg"));
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

    /**
     * uri转bitmap
     *
     * @param uri
     * @return
     */
    private Bitmap getBitmapFromUri(Uri uri) {
        try {
            // 读取uri所在的图片
            BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
            bitmapOptions.inSampleSize = 4;
            Bitmap bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, bitmapOptions);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 计算相隔天数
     */
    public int daysBetween(String dateBegin, String dateEnd) {
        Date dBegin = null;
        Date dEnd = null;
        long daysBetween = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dBegin = sdf.parse("" + dateBegin);
            dEnd = sdf.parse("" + dateEnd);
            daysBetween = (dEnd.getTime() - dBegin.getTime()) / (3600 * 24 * 1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int) daysBetween;
    }

    /**
     * 获得日期方法(年月日)
     */
    public String getDate(int dateIndex) {
        return userMessageList.get(periodBeginIndexList.get(dateIndex).getIndex()).getDate().substring(0, 10);
    }

    /**
     * 判断是否失眠、生病、吃药、喝酒
     */
    public int daily(int flag, int index) {
        if (((userMessageList.get(index).getCondition()) & (1 << flag - 1)) != 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 递增天数
     */
    public String addDateDay(String date) {
        String getDateDay = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date getDate;
        try {
            getDate = sdf.parse(date);
            getDate = addDate(getDate, 1);
            getDateDay = sdf.format(getDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return getDateDay;
    }

    public static Date addDate(Date d, long day) throws ParseException {
        long time = d.getTime();
        day = day * 24 * 60 * 60 * 1000;
        time += day;
        return new Date(time);
    }
}
